<?php
header("Content-Type: application/json; charset=utf-8");
// 关键：启动Session，确保角色能存入
session_start();
require_once '../config/db.php';

$action = $_GET['action'] ?? '';

// 登录逻辑（核心：获取并存储角色）
if ($action === 'login') {
  $data = json_decode(file_get_contents('php://input'), true);
  $username = trim($data['username'] ?? '');
  $password = trim($data['password'] ?? '');

  if (empty($username) || empty($password)) {
    echo json_encode(['status' => 'error', 'message' => '用户名和密码不能为空']);
    exit;
  }

  try {
    // 关键：查询时必须包含role字段
    $stmt = $pdo->prepare("SELECT id, username, password, role FROM users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if (!$user || !password_verify($password, $user['password'])) {
      echo json_encode(['status' => 'error', 'message' => '用户名或密码错误']);
      exit;
    }

    // 核心修复：将角色存入Session（必须执行这一步）
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['role'] = $user['role']; // 存储角色到Session

    // 返回角色给前端（可选，但确保后端已存储）
    echo json_encode([
      'status' => 'success',
      'message' => '登录成功',
      'role' => $user['role']
    ]);
  } catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => '登录失败：' . $e->getMessage()]);
  }
  exit;
}

// 退出登录（清除Session）
if ($action === 'logout') {
  session_destroy();
  echo json_encode(['status' => 'success', 'message' => '退出成功']);
  exit;
}

echo json_encode(['status' => 'error', 'message' => '无效操作']);
